package com.epfresh.api.http;

import android.util.Log;

import com.epfresh.api.http.volley.AuthFailureError;
import com.epfresh.api.http.volley.NetworkResponse;
import com.epfresh.api.http.volley.Request;
import com.epfresh.api.http.volley.Response;
import com.epfresh.api.http.volley.toolbox.HttpHeaderParser;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wzh on 2016/3/15.
 */
public class StringRequest extends Request<String> {

    private Map<String, String> headers;
    private Object data;

    public StringRequest(int method, Map<String, String> headers, String url, Object data,
                         Response.ErrorListener listener) {
        super(method, url, listener);
        this.data = data;
        this.headers = headers;

    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        if (headers == null) {
            headers = new HashMap<>();
        }
        headers.put("Accept", "application/json");
        headers.put("Content-Type", "application/json; charset=UTF-8");
        return headers;
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        if (data != null) {
            try {
                String jsonStr = data.toString();
//                Log.d("test", "requestSilent:" + jsonStr);
                if (jsonStr != null) {
                    return jsonStr.getBytes("utf-8");
                } else {
                    //@link{RequestEntity} Gson to string error

                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return super.getBody();
    }

    // UI线程执行
    @Override
    protected void deliverResponse(String response) {

//        Log.d("test", "ui_response:" + response + "");
    }

    // 子线程执行
    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        byte[] data = response.data;
        try {
            String parsed = new String(data, "utf8");
//            Log.d("test", "response:" + parsed + "");

            if (parsed != null) {
                return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
            }
        } catch (UnsupportedEncodingException e) {
            //编码错误
            e.printStackTrace();
        }
        return null;
    }

}
